﻿using Common;
using MESAPI;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PLC.Model;
using System.Collections.Generic;
using System.Text.Json;
using static Common.LogHelper;

namespace AppMesPlc.DAL
{
    public static class QueryDal
    {
        public static string rootPath = AppDomain.CurrentDomain.BaseDirectory;
        /// <summary>
        /// 获取设备信息
        /// </summary>
        /// <returns></returns>
        public static List<MACHINEINFO> GetMachineInfos()
        {
            string jsonString = File.ReadAllText(rootPath + "setting/machineinfo.json");
            return System.Text.Json.JsonSerializer.Deserialize<List<MACHINEINFO>>(jsonString);
        }


        /// <summary>
        /// 修改设备信息
        /// </summary>
        /// <returns></returns>
        public static bool UpdateMachineInfos(string comName)
        {
            try
            {
                JsonSerializerOptions options = new()
                {
                    PropertyNameCaseInsensitive = true,
                    WriteIndented = true // 保持格式化的输出
                };
                var list = GetMachineInfos();
                list[0].IpAddress = $"{comName},9600";

                string path = Path.Combine(rootPath, "setting", "machineinfo.json");
                string updatedJson = System.Text.Json.JsonSerializer.Serialize(list, options);
                File.WriteAllText(path, updatedJson);
                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw;
            }
        }


        /// <summary>
        /// 获取plc信息
        /// </summary>
        /// <returns></returns>
        public static List<plcptseting> Getplcptseting()
        {
            string jsonString = File.ReadAllText(rootPath + "setting/plcptseting.json");
            return System.Text.Json.JsonSerializer.Deserialize<List<plcptseting>>(jsonString);
        }
        /// <summary>
        /// 获取plc连接信息
        /// </summary>
        /// <returns></returns>
        public static JObject GetAppsettings()
        {
            string appsettings = File.ReadAllText(rootPath + "setting/appsettings.json");
            return JObject.Parse(appsettings);
        }
        /// <summary>
        /// 修改plc连接信息
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="newValue"></param>
        public static void UpdateAppsetting(string propertyName, object newValue)
        {
            string appsettingsPath = Path.Combine(rootPath, "setting", "appsettings.json");
            JObject appsettings = GetAppsettings();
            appsettings["plc"][propertyName] = JToken.FromObject(newValue);
            string updatedContent = appsettings.ToString(Formatting.Indented);
            File.WriteAllText(appsettingsPath, updatedContent);
        }

        /// <summary>
        /// 获取上下限
        /// </summary>
        /// <returns></returns>
        public static List<STANDARDSETING> Getstandardseting()
        {
            string jsonString = File.ReadAllText(rootPath + "setting/standardseting.json");
            return System.Text.Json.JsonSerializer.Deserialize<List<STANDARDSETING>>(jsonString);
        }

        public static bool UpdateStandardseting(STANDARDSETING standardseting)
        {
            try
            {
                JsonSerializerOptions options = new()
                {
                    PropertyNameCaseInsensitive = true,
                    WriteIndented = true // 保持格式化的输出
                };
                List<STANDARDSETING> list = new List<STANDARDSETING>(); 
                list.Add(standardseting);
                string path = Path.Combine(rootPath, "setting", "standardseting.json");
                string updatedJson = System.Text.Json.JsonSerializer.Serialize(list, options);
                File.WriteAllText(path, updatedJson);
                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw;
            }
        }

        /// <summary>
        /// 进站
        /// </summary>
        /// <param name="xmlData"></param>
        /// <returns></returns>
        public static string CheckSFC(string xmlData)
        {
            using (var client = new MESServicerClient())
            {
                try
                {
                    return client.Check_SFC(xmlData);
                }
                catch (Exception ex)
                {
                    // 处理异常并记录日志
                    WriteLog(NLogLevel.Error, $"MES接口调用失败: {ex.Message}");
                    return $"ERROR:{ex.Message}";
                }
            }
        }



        /// <summary>
        /// 出站
        /// </summary>
        /// <param name="xmlData"></param>
        /// <returns></returns>
        public static string InsertSFC(string xmlData)
        {
            using (var client = new MESServicerClient())
            {
                try
                {
                    return client.Insert_SFC(xmlData);
                }
                catch (Exception ex)
                {
                    // 处理异常并记录日志
                    WriteLog(NLogLevel.Error, $"MES接口调用失败: {ex.Message}");
                    return $"ERROR:{ex.Message}";
                }
            }
        }

        /// <summary>
        /// 不良品登记
        /// </summary>
        /// <param name="xmlData"></param>
        /// <returns></returns>
        public static string PScrapINFO(string xmlData)
        {
            using (var client = new MESServicerClient())
            {
                try
                {
                    return client.P_Scrap_INFO(xmlData);
                }
                catch (Exception ex)
                {
                    // 处理异常并记录日志
                    WriteLog(NLogLevel.Error, $"MES接口调用失败: {ex.Message}");
                    return $"ERROR:{ex.Message}";
                }
            }
        }

        /// <summary>
        /// 查询工序
        /// </summary>
        /// <param name="xmlData"></param>
        /// <returns></returns>
        public static string GetProcessInfo(string xmlData)
        {
            using (var client = new MESServicerClient())
            {
                try
                {
                    return client.Get_ProcessInfo(xmlData);
                }
                catch (Exception ex)
                {
                    // 处理异常并记录日志
                    WriteLog(NLogLevel.Error, $"MES接口调用失败: {ex.Message}");
                    return $"ERROR:{ex.Message}";
                }
            }
        }

        /// <summary>
        /// 查询工位
        /// </summary>
        /// <param name="xmlData"></param>
        /// <returns></returns>
        public static string GetStationInfo(string xmlData)
        {
            using (var client = new MESServicerClient())
            {
                try
                {
                    return client.Get_StationInfo(xmlData);
                }
                catch (Exception ex)
                {
                    // 处理异常并记录日志
                    WriteLog(NLogLevel.Error, $"MES接口调用失败: {ex.Message}");
                    return $"ERROR:{ex.Message}";
                }
            }
        }
        /// <summary>
        /// 查询工单
        /// </summary>
        /// <param name="xmlData"></param>
        /// <returns></returns>
        public static string GetOrderInfo(string xmlData)
        {
            using (var client = new MESServicerClient())
            {
                try
                {
                    return client.Get_OrderInfo(xmlData);
                }
                catch (Exception ex)
                {
                    // 处理异常并记录日志
                    WriteLog(NLogLevel.Error, $"MES接口调用失败: {ex.Message}");
                    return $"ERROR:{ex.Message}";
                }
            }
        }

        /// <summary>
        /// 查询采集项目
        /// </summary>
        /// <param name="xmlData"></param>
        /// <returns></returns>
        public static string GetDisInfo(string xmlData)
        {
            using (var client = new MESServicerClient())
            {
                try
                {
                    return client.Get_DisInfo(xmlData);
                }
                catch (Exception ex)
                {
                    // 处理异常并记录日志
                    WriteLog(NLogLevel.Error, $"MES接口调用失败: {ex.Message}");
                    return $"ERROR:{ex.Message}";
                }
            }
        }


        public static string CheckUser(string xmlData)
        {
            using (var client = new MESServicerClient())
            {
                try
                {
                    return client.Check_User(xmlData);
                }
                catch (Exception ex)
                {
                    // 处理异常并记录日志
                    WriteLog(NLogLevel.Error, $"MES接口调用失败: {ex.Message}");
                    return $"ERROR:{ex.Message}";
                }
            }
        }

    }
}
